var express = require('express');
var router = express.Router();
var {  addressModel  }=require('../modle/modle')
let {randomCode,sendCode}=require('./code1')
const path = require('path')
const multer = require('multer')
const multiparty = require('multiparty');
/* GET home page. */
router.get('/addresslist',async(req,res)=>{
  const mess=await addressModel.find() 
  console.log(mess);
  
  res.send({
      code:200,
      data:mess,
   
  })
})

//图片上传
// 配置Multer存储
router.post('/uploadimg', async (req, res) => {
  let form = new multiparty.Form();//创建表单对象
  form.uploadDir = 'upload';//设置上传目录
  form.parse(req , async (err, fields, files) => {  //解析请求体：
    if (err) {//错误处理
      return res.status(500).send({ code: 500, msg: '上传失败', error: err.message });
    }

    let filePath = files.image[0].path;//获取文件路径


    //计算文件相对于根目录的路径，即去掉绝对路径前缀的部分。
    let relativePath = `http://localhost:8000/${filePath}`;

    res.send({//成功响应
      code: 200,
      path: relativePath,
      base:filePath
    });
  });
});

router.get("/code", async (req, res) => {
  let code = randomCode(4);//生成6位数字随机验证码
  sendCode(req.query.phone, code, function (success) {
    if (success) {
      res.send({
        code: 200,
        msg: "短信验证码发送成功",
        codes: code
      });
    } else {
      res.send("短信验证码发送失败");
    }
  })
})
module.exports = router;
